{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Copyright 2014 Brett Slatkin, Pearson Education Inc.\n",
    "#\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License.\n",
    "\n",
    "# Preamble to mimick book environment\n",
    "import logging\n",
    "from pprint import pprint\n",
    "from sys import stdout as STDOUT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 1\n",
    "import json\n",
    "\n",
    "class Serializable(object):\n",
    "    def __init__(self, *args):\n",
    "        self.args = args\n",
    "\n",
    "    def serialize(self):\n",
    "        return json.dumps({'args': self.args})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Object:     Point2D(5, 3)\n",
      "Serialized: {\"args\": [5, 3]}\n"
     ]
    }
   ],
   "source": [
    "# Example 2\n",
    "class Point2D(Serializable):\n",
    "    def __init__(self, x, y):\n",
    "        super().__init__(x, y)\n",
    "        self.x = x\n",
    "        self.y = y\n",
    "\n",
    "    def __repr__(self):\n",
    "        return 'Point2D(%d, %d)' % (self.x, self.y)\n",
    "\n",
    "point = Point2D(5, 3)\n",
    "print('Object:    ', point)\n",
    "print('Serialized:', point.serialize())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 3\n",
    "class Deserializable(Serializable):\n",
    "    @classmethod\n",
    "    def deserialize(cls, json_data):\n",
    "        params = json.loads(json_data)\n",
    "        return cls(*params['args'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Before:     BetterPoint2D(5, 3)\n",
      "Serialized: {\"args\": [5, 3]}\n",
      "After:      BetterPoint2D(5, 3)\n"
     ]
    }
   ],
   "source": [
    "# Example 4\n",
    "class BetterPoint2D(Deserializable):\n",
    "    def __init__(self, x, y):\n",
    "        super().__init__(x, y)\n",
    "        self.x = x\n",
    "        self.y = y\n",
    "\n",
    "    def __repr__(self):\n",
    "        return 'BetterPoint2D(%d, %d)' % (self.x, self.y)\n",
    "\n",
    "point = BetterPoint2D(5, 3)\n",
    "print('Before:    ', point)\n",
    "data = point.serialize()\n",
    "print('Serialized:', data)\n",
    "after = BetterPoint2D.deserialize(data)\n",
    "print('After:     ', after)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 5\n",
    "class BetterSerializable(object):\n",
    "    def __init__(self, *args):\n",
    "        self.args = args\n",
    "\n",
    "    def serialize(self):\n",
    "        return json.dumps({\n",
    "            'class': self.__class__.__name__,\n",
    "            'args': self.args,\n",
    "        })\n",
    "\n",
    "    def __repr__(self):\n",
    "        return '%s(%s)' % (\n",
    "            self.__class__.__name__,\n",
    "            ', '.join(str(x) for x in self.args))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 6\n",
    "registry = {}\n",
    "\n",
    "def register_class(target_class):\n",
    "    registry[target_class.__name__] = target_class\n",
    "\n",
    "def deserialize(data):\n",
    "    params = json.loads(data)\n",
    "    name = params['class']\n",
    "    target_class = registry[name]\n",
    "    return target_class(*params['args'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 7\n",
    "class EvenBetterPoint2D(BetterSerializable):\n",
    "    def __init__(self, x, y):\n",
    "        super().__init__(x, y)\n",
    "        self.x = x\n",
    "        self.y = y\n",
    "\n",
    "register_class(EvenBetterPoint2D)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Before:     EvenBetterPoint2D(5, 3)\n",
      "Serialized: {\"class\": \"EvenBetterPoint2D\", \"args\": [5, 3]}\n",
      "After:      EvenBetterPoint2D(5, 3)\n"
     ]
    }
   ],
   "source": [
    "# Example 8\n",
    "point = EvenBetterPoint2D(5, 3)\n",
    "print('Before:    ', point)\n",
    "data = point.serialize()\n",
    "print('Serialized:', data)\n",
    "after = deserialize(data)\n",
    "print('After:     ', after)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 9\n",
    "class Point3D(BetterSerializable):\n",
    "    def __init__(self, x, y, z):\n",
    "        super().__init__(x, y, z)\n",
    "        self.x = x\n",
    "        self.y = y\n",
    "        self.z = z\n",
    "\n",
    "# Forgot to call register_class! Whoops!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 10\n",
    "try:\n",
    "    point = Point3D(5, 9, -4)\n",
    "    data = point.serialize()\n",
    "    deserialize(data)\n",
    "except:\n",
    "    logging.exception('Expected')\n",
    "else:\n",
    "    assert False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 11\n",
    "class Meta(type):\n",
    "    def __new__(meta, name, bases, class_dict):\n",
    "        cls = type.__new__(meta, name, bases, class_dict)\n",
    "        register_class(cls)\n",
    "        return cls\n",
    "\n",
    "class RegisteredSerializable(BetterSerializable, metaclass=Meta):\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Before:     Vector3D(10, -7, 3)\n",
      "Serialized: {\"class\": \"Vector3D\", \"args\": [10, -7, 3]}\n",
      "After:      Vector3D(10, -7, 3)\n"
     ]
    }
   ],
   "source": [
    "# Example 12\n",
    "class Vector3D(RegisteredSerializable):\n",
    "    def __init__(self, x, y, z):\n",
    "        super().__init__(x, y, z)\n",
    "        self.x, self.y, self.z = x, y, z\n",
    "\n",
    "v3 = Vector3D(10, -7, 3)\n",
    "print('Before:    ', v3)\n",
    "data = v3.serialize()\n",
    "print('Serialized:', data)\n",
    "print('After:     ', deserialize(data))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
